<template>
  <el-dialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    title="添加产品"
    width="80%"
    top="5vh"
    @open="handleDialogOpen"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-container style="height: 75vh;">
      <!-- 左侧: 产品分类 -->
      <el-aside width="250px" style=" display: flex; padding-right: 20px;border-right: 1px solid #eee; flex-direction: column;">
        <h3 style="margin-top: 0; margin-bottom: 10px; font-weight: 500;">产品分类</h3>
        <el-input v-model="categorySearch" placeholder="请输入分类" clearable />
        <el-tree
          :data="categoryData"
          :props="{ label: 'label', children: 'children' }"
          :filter-node-method="filterNode"
          ref="treeRef"
          node-key="id"
          default-expand-all
          highlight-current
          @node-click="handleCategoryClick"
          class="category-tree"
        />
      </el-aside>

      <!-- 右侧: 产品列表与搜索 -->
      <el-main style="display: flex; flex-direction: column;">
        <el-input
          v-model="searchParams.keyword"
          placeholder="产品品号/产品名称"
          clearable
          @keyup.enter="handleSearch"
          @clear="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>

        <el-table
          :data="tableData"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          ref="multipleTableRef"
          border
          height="100%"
          style="width: 100%; margin-top: 20px; flex-grow: 1;"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="partNumber" label="产品品号" width="150" />
          <el-table-column prop="productName" label="产品名称" width="150" />
          <el-table-column prop="productCategory" label="产品分类" width="100" />
          <el-table-column prop="flowchartNumber" label="流程图号" width="150" />
          <el-table-column prop="specifications" label="产品规格" show-overflow-tooltip />
          <el-table-column prop="description" label="产品描述" show-overflow-tooltip />
          <el-table-column prop="unit" label="单位" width="80" align="center"/>
        </el-table>

        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 20px; justify-content: flex-end;"
        />
      </el-main>
    </el-container>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:modelValue', false)">取 消</el-button>
        <el-button type="primary" @click="handleConfirmAdd">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { ProductSpecificationsApi } from '@/api/productspecifications/index';


// --- Props & Emits ---
const props = defineProps({
  modelValue: { // 使用 v-model 控制显示/隐藏
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(['update:modelValue', 'confirm']);

// --- 弹框内部状态 ---
const loading = ref(false);
const treeRef = ref(null);
const multipleTableRef = ref(null);
const categorySearch = ref('');
const categoryData = ref([
  { id: 'all', label: '全部' },
  { id: 'finished', label: '成品' },
  { id: 'semi-finished', label: '半成品' },
  { id: 'raw', label: '原材料' },
]);
const tableData = ref([]);
const pagination = reactive({ currentPage: 1, pageSize: 10, total: 0 });
const searchParams = reactive({ keyword: '', category: '全部' });
const selectedProducts = ref([]);

watch(categorySearch, (val) => treeRef.value?.filter(val));
const filterNode = (value, data) => !value || data.label.includes(value);

const fetchProductList = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,    // 页码
      size: pagination.pageSize,       // 每页数量
      keyword: searchParams.keyword,   // 搜索关键词
      category: searchParams.category  // 产品分类
    };
    // 调用真实接口
    const response = await ProductSpecificationsApi.getProductSpecificationsPage(params);
    // 假设接口返回格式：{ list: 数据数组, total: 总条数 }
    tableData.value = response.list;
    pagination.total = response.total;
  } catch (error) {
    console.error("获取产品列表失败:", error);
    ElMessage.error("获取产品列表失败");
  } finally {
    loading.value = false;
  }
};

// --- 事件处理器 ---
const handleDialogOpen = () => {
  nextTick(() => {
    treeRef.value?.setCurrentKey('all');
    multipleTableRef.value?.clearSelection();
  });
  searchParams.keyword = '';
  searchParams.category = '全部';
  pagination.currentPage = 1;
  fetchProductList();
};

const handleCategoryClick = (data) => {
  if (searchParams.category === data.label) return;
  searchParams.category = data.label;
  pagination.currentPage = 1;
  fetchProductList();
};

const handleSearch = () => {
  pagination.currentPage = 1;
  fetchProductList();
};

const handleSizeChange = (size) => { pagination.pageSize = size; fetchProductList(); };
const handleCurrentChange = (page) => { pagination.currentPage = page; fetchProductList(); };
const handleSelectionChange = (selection) => { selectedProducts.value = selection.map(item => {
    const { id, ...rest } = item; // 解构出id和剩余属性
    return { ...rest, productSpecId: id }; // 剩余属性 + 重命名后的productSpecId
  }); };

const handleConfirmAdd = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请至少选择一个产品');
    return;
  }
  emit('confirm', selectedProducts.value);
  emit('update:modelValue', false);
};
</script>

<style scoped>
.category-tree {
    margin-top: 10px;
    flex-grow: 1;
    overflow-y: auto;
}

:deep(.el-tree-node__content) {
  height: 36px;
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  background-color: #f0f9eb; /* 图片中的淡绿色 */
}
</style>